package com.wellview.template.presenter;



import com.wellview.template.Constant;
import com.wellview.template.bean.UpdateBean;
import com.wellview.template.logger.Logger;
import com.wellview.template.modle.BaseBehavior;

import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.Call;

/**
 * Created by Administrator on 2017/8/30 0030.
 */

public class JSProvider extends BaseProvider {

    public void checkUpdate(final ResultListener listener) {
        BaseBehavior.Clause updateClause = new BaseBehavior.Clause().method(BaseBehavior.Clause.Method.GET);
        setUrl(Constant.URL_UPDATE).addClause(updateClause).execute(new ResultListener<String>() {
            @Override
            public void inProgress(float progress, long total, int id) {

            }

            @Override
            public void onError(Call call, Exception e, int id) {
                Logger.i(TAG, "checkUpdateError : ");
                listener.onError(call,e,id);
            }

            @Override
            public void onResponse(String response, int id) {
                Logger.i(TAG, "doUpdate " + response);
                listener.onResponse(ParseUpMessage(response),id);

            }
        });
    }


    private UpdateBean ParseUpMessage(String response) {
        try {
            JSONObject responseJson = new JSONObject(response);
            JSONObject status = responseJson.optJSONObject("Status");
            if (status == null){
                return null;
            }
            if (!"1".equals(status.optString("Code"))){
                return null;
            }
            JSONObject data = responseJson.optJSONObject("Data");
            if (data != null) {
                String name = data.optString("Name");
                String Version = data.optString("Version");
                String Url = data.optString("Url");
                return new UpdateBean(name,Version,Url);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }


}
